<?php

/**
 * TechnoDK_LogFile
 * Class used for logging events such as login
 * Author: Anthony De Leon AKA "Crackerjack"
 * Group: TechnoCoders
 */
class TechnoDK_LogFile
{
	/**
	 * Path of the specified file
	 *
	 * @var String
	 */
	private $_file;
	
	/**
	 * Constructor for Techno_LogFile object
	 * It checks if the file specified is a TCL file
	 */
	public function __construct($file)
	{
		if(pathinfo($file,PATHINFO_EXTENSION) == 'tcl'){
			$this->_file = $file;
		} else {
			throw new Exception('Must be a tcl file');
		}	
	}
	
	/**
	 * Get all logs from file
	 * return type : array
	 */
	public function getLogs()
	{
		$logs = array();
		$tmp_logs = file($this->_file);
		foreach($tmp_logs as $line_num => $log){
			$log = explode(",",$log);
			foreach($log as $value){
				$value = explode(":",$value);
				$logs[$line_num][trim($value[0])] = trim($value[1]);
			}
		}
		return $logs;	
	}
	
	/**
	 * It serves as the insert function
	 *
	 * @param string or array containing the data to be inserted
	 */
	public function log($data)
	{
		if(is_array($data)){
			$tmp = array();
			foreach($data as $key => $value){
				$tmp[]  = trim($key).':'.($value);
			}
			$data = implode(',',$tmp);
		}
		$data .= "\n";
		if(file_put_contents($this->_file,$data,FILE_APPEND)){
			return true;
		}
		return false;
	}
	
	/**
	 * Delete all logs from file
	 *
	 */
	public function deleteLogs()
	{
		if(file_put_contents($this->_file,"")){
			return true;
		}
		return false;
	}
	
	/**
	 * Get logs from file by specifying the particular field
	 *
	 * @param String $find
	 * @param String $where
	 * @param Integer $limit
	 */
	public function getLogsByField($find, $where, $limit = 0)
	{
		$logs = array();
		$tmp_logs = file($this->_file);
		$i = 0;
		foreach($tmp_logs as $line_num => $log){
			preg_match("/{$where}:{$find}/",$log,$match);
			if(!empty($match)){
				$log = explode(",",$log);
				foreach($log as $value){
					$value		= explode(":",$value);
					$value[0]	= trim($value[0]);
					$value[1]	= trim($value[1]);
					$logs[$line_num][$value[0]] = $value[1];
				}
			}
		}
		if($limit != 0){
			$logs = array_slice($logs,0,$limit);
		}
		return $logs;
	}
	
	/**
	 *
	 *
	 */
	public function deleteLogsByField($find, $where)
	{
		$new_content = '';
		$logs = file($this->_file);
		$affected_lines = 0;
		foreach($logs as $line => $log){
			preg_match("/{$where}:{$find}/",$log,$match);
			if(empty($match)){
				$new_content .= $log;
			} else {
				$affected_lines++;
			}
		}
		if(file_put_contents($this->_file, $new_content)){
			return $affected_lines;
		}
		return false;
	}
	
	/**
	 * Enter description here...
	 *
	 */
	public function lock()
	{
		
	}
	
	/**
	 * 
	 *
	 */
	public function deleteFile()
	{
		
	}
	
}



?>